#!/bin/bash

action=$1
if [ "$action" == "" ]; then action=安装; fi

SWNAME=mesa
swVer=24.3.0

. ./scripts/common.sh

DEB_PATH=./downloads/${SWNAME}-${swVer}.tar.xz
SRC_DIR="${ZZSWMGR_MAIN_DIR}/tmp/${SWNAME}-${swVer}"
PATCH_D="${ZZSWMGR_MAIN_DIR}/tmp/${SWNAME}-${swVer}-patchs"
RLT_DIR="${ZZSWMGR_MAIN_DIR}/tmp/${SWNAME}-${swVer}-out-arm64"
echo "  SRC_DIR: ${SRC_DIR}"
echo "PATCH_DIR: ${PATCH_D}"
echo "  RLT_DIR: ${RLT_DIR}"


declare -a PATCHLIST=(\
	0002-linux-fix-for-getprogname.patch \
	0003-linux-fix-for-anon-file.patch \
	0007-linux-dri3.patch \
	0010-fix-zink.patch \
	0011-freedreno-drm-kgsl-Add-KGSL-backend-for-freedreno.patch \
	0012-freedreno-drm-Add-more-APIs-to-per-backend-API.patch \
	0013-fix-bad-syscall.patch \
	0014-freedreno-HACK-GL_ARB_timer_query.patch \
	0015-termux-x11-kgsl.patch \
)

function detect_adreno_gpu() {
	. ${app_home}/hwinfo.rc
	IS_ADRENO_GPU=0
	if [[ "${device_gpu_name}" == *"dreno"* ]]; then
		IS_ADRENO_GPU=1
	fi
	if [ $IS_ADRENO_GPU -ne 1 ]; then
		echo "当前设备的GPU不是骁龙系列，编译了也没用"
		exit 2
	fi
}

function maketxz() {
	if [ -d ${RLT_DIR}/DEBIAN ]; then
		rm -rf ${RLT_DIR}/DEBIAN
	fi

	TXZ_OUT=${RLT_DIR}.tar.xz
	rm -rf ${TXZ_OUT}
	cd ${RLT_DIR} && tar -cJf ${TXZ_OUT}  .

	if [ -f ${TXZ_OUT} ]; then
		echo "xz包生成成功 => ${TXZ_OUT}"
		open ${RLT_DIR}/..  &
		return 0
	fi
}


function makedeb() {
	# 参考：https://blog.csdn.net/badbayyj/article/details/129353140

	DEB_DIR=${RLT_DIR}
	DEB_OUT=${DEB_DIR}.deb
	mkdir -p ${DEB_DIR}/DEBIAN

	echo "Package: mesa-freedreno"            > ${DEB_DIR}/DEBIAN/control
	echo "Version: ${swVer}"                  >>${DEB_DIR}/DEBIAN/control
	echo "Architecture: arm64"                >>${DEB_DIR}/DEBIAN/control
	echo "Maintainer: droidvm"                >>${DEB_DIR}/DEBIAN/control
	echo "Description: opengl and vulkan libs">>${DEB_DIR}/DEBIAN/control
	# echo "Replaces: *"                      >>${DEB_DIR}/DEBIAN/control
	# echo "Depends: libc6:armhf"             >>${DEB_DIR}/DEBIAN/control
	chmod 755 ${DEB_DIR}/DEBIAN/control

	# 打包！
	dpkg -b ${DEB_DIR}

	if [ -f ${DEB_OUT} ]; then
		echo "DEB包生成成功 => ${DEB_OUT}"
		open ${RLT_DIR}/..  &
		return 0
	fi

	return 1
}

function gen_vscode_debug_cfgfile() {
	# 请注意！！！！！
	# vscode 中，最新的 "C/C++ 扩展" 不能正常启动gdb，
	# 请改装 "Kylin-ID team" 那个调试插件，即黄色小虫的那个图标，或者搜索 "C/C++ Debug"，再找到 kylin 那个
	mkdir -p ${SRC_DIR}/.vscode >/dev/null
	cat <<- EOF >> ${SRC_DIR}/.vscode/launch.json
		{
			"version": "0.2.0",
			"configurations": [
			{
				"name": "调试",
				"type": "cppdbg",
				"request": "launch",
				"args": [],
				"stopAtEntry": false,
				"externalConsole": false,
				"cwd": "${workspaceFolder}",
				"program": "/usr/bin/vkcube",
				"MIMode": "gdb",
				"miDebuggerPath": "/usr/bin/gdb",
				"environment": [
				{ "name": "DISPLAY", "value": ":4"},
				{ "name": "LD_LIBRARY_PATH", "value": "/exbin/tools/zzswmgr/tmp/mesa-24.3.0-out-arm64/usr/lib/aarch64-linux-gnu:/exbin/tools/zzswmgr/tmp/mesa-24.3.0-out-arm64/usr/lib/aarch64-linux-gnu/dri" },
				{ "name": "MESA_LOADER_DRIVER_OVERRIDE", "value": "kgsl"},
				{ "name": "VK_ICD_FILENAMES", "value": "/exbin/tools/zzswmgr/tmp/mesa-24.3.0-out-arm64/usr/share/vulkan/icd.d/freedreno_icd.aarch64.json"},
				{ "name": "TU_DEBUG", "value": "noconform"},
				],
				"setupCommands": [
				{
					"description": "Enable pretty-printing for gdb",
					"text": "-enable-pretty-printing",
					"ignoreFailures": true
				}
				]
			}
			]
		}
	EOF
}

function sw_download() {

	tmpdns=`cd /exbin && droidexec ./vm_getHostByName.sh archive.mesa3d.org ${GITHUB_PROXY_HOST}`
	exit_if_fail $? "DNS解析失败"
	echo "$tmpdns" >> /etc/hosts

	if [ ! -d ${SRC_DIR} ]; then

		swUrl="https://archive.mesa3d.org/mesa-${swVer}.tar.xz"
		download_file2 "${DEB_PATH}" "${swUrl}"
		exit_if_fail $? "下载失败，网址：${swUrl}"

		[ -d ${PATCH_D} ] || mkdir -p ${PATCH_D}
		exit_if_fail $? "文件夹创建失败：${PATCH_D}"

		echo "正在下载 kgsl 补丁文件. . ."
		for PATCH_ITEM in "${PATCHLIST[@]}"; do
			swUrl="${GITHUB_PROXY_HTTP}https://github.com/droidvm/mesa-freedreno-patchs/raw/refs/heads/main/freedreno-kgsl-patchs-for-24.3.0/${PATCH_ITEM}"
			download_file2 "${PATCH_D}/${PATCH_ITEM}" "${swUrl}"
			exit_if_fail $? "下载失败，软件包：${SW_ITEM}"
		done

		# # 补丁处理，无效，会全部替换，本意是只替换 patch 中需要的地方
		# sed -i "s|__ANDROID__|DROIDVM1|" "${PATCH_D}/"*
		# sed -i "s|__TERMUX__|DROIDVM2|"  "${PATCH_D}/"*

		echo "正在解压源码. . ."
		mkdir -p ${SRC_DIR}
		tar -xJf ${DEB_PATH} --overwrite -C ${SRC_DIR}/..
		exit_if_fail $? "安装失败，软件包：${DEB_PATH1}"

		command -v patch >/dev/null 2>&1 || sudo apt-get install -y patch
		exit_if_fail $? "patch工具安装失败"

		echo "正在修改源码"
		cd ${SRC_DIR}
		for PATCH_ITEM in "${PATCHLIST[@]}"; do
			echo "patch -p1 < ""${PATCH_D}/${PATCH_ITEM}"
			patch -p1 < "${PATCH_D}/${PATCH_ITEM}"
			if [ $? -ne 0 ]; then
				rm -rf ${SRC_DIR}
				false
				exit_if_fail $? "源码修改失败"
			fi
		done

		# # 方便在vscode中调试，vscode扩展商店搜索 "C/C++ Debug"，再找到 kylin 那个
		# gen_vscode_debug_cfgfile

		# 补丁生成参考：
		# https://geek-docs.com/git/git-questions/331_git_how_to_create_git_patch_from_two_files.html#google_vignette
	else
		:
	fi

}

function sw_compile() {

	# sudo apt-get install -y dpkg-dev xz-utils mesa-utils
	sudo apt-get install -y xz-utils git patchelf pip zip meson ninja-build flex bison libarchive-dev glslang-tools python3-mako \
	libxcb-randr0-dev  libdrm-dev libxcb-glx0-dev libx11-xcb-dev libxcb-dri3-dev libxcb-present-dev \
	build-essential git python3-mako libdrm-dev libexpat1-dev libwayland-dev \
	libwayland-egl-backend-dev libx11-xcb-dev libxcb-dri2-0-dev libxcb-dri3-dev libxcb-present-dev \
	libxcb-randr0-dev libxcb-shm0-dev libxcb-sync-dev libxcb-xfixes0-dev libxrandr-dev libxshmfence-dev \
	libxxf86vm-dev bison flex libssl-dev ninja-build meson pkg-config
	exit_if_fail $? "依赖库安装失败 (此动作效于: sudo apt build-dep -y mesa)"

	cd ${SRC_DIR}
	pwd

	DIR_NAME=build-proot-linux-aarch64

	# release,debug
	# https://mesonbuild.com/Builtin-options.html 提到 c_args 中的多个参数用逗号做间隔
	OPTIONS="-Dprefix=/usr -Dbuildtype=release -Dplatforms=x11 \
	-Dgallium-drivers=zink,freedreno \
	-Dvulkan-drivers=freedreno \
	-Dvulkan-beta=true -Dfreedreno-kmds=kgsl -Dgbm=enabled \
	-Dshared-glapi=enabled -Dglx=dri -Dgallium-xa=enabled \
	-Dopengl=true -Degl=enabled -Dglx-direct=true \
	"

	echo "正在对源码进行编译前配置。禁用不需要的选项，可以减少编译量 ..." $'\n'
	rm -rf   ${RLT_DIR}
	meson setup  --reconfigure  ${DIR_NAME} ${OPTIONS} -Dc_args="['-DDROIDVM1=1', '-DDROIDVM2=1', '-DDROIDVM3=1']"
	exit_if_fail $? "meson config fail"

	echo "正在编译 ..." $'\n'
	ninja -C ${DIR_NAME} 2>&1
	exit_if_fail $? "ninja build fail"

	echo "正在复制编译好的文件 ..." $'\n'
	DESTDIR=${RLT_DIR} ninja -C ${DIR_NAME} install
	exit_if_fail $? "ninja install fail"

	echo "编译成功，已将文件复制到: ${RLT_DIR}"

	echo "正在打包为.tar.xz压缩包 ..." $'\n'
	maketxz
	exit_if_fail $? "txz包打包失败"
	# echo "正在打包为.deb压缩包 ..." $'\n'
	# makedeb
	# exit_if_fail $? "deb包打包失败"

	echo "如果将编译好的文件放到别的文件夹"
	echo "请相应的调整 /usr/share/vulkan/icd.d/freedreno_icd.aarch64.json 文件中so库文件的搜索路径"

	: '

	# glmark2 测试,
	RLT_DIR=/exbin/tools/zzswmgr/tmp/mesa-24.3.0-out-arm64
	export LD_LIBRARY_PATH=$RLT_DIR/usr/lib/aarch64-linux-gnu:$RLT_DIR/usr/lib/aarch64-linux-gnu/dri
	export MESA_LOADER_DRIVER_OVERRIDE=kgsl
	export VK_ICD_FILENAMES=$RLT_DIR/usr/share/vulkan/icd.d/freedreno_icd.aarch64.json
	export TU_DEBUG=noconform
	export MESA_DEBUG=1
	export LIBGL_DEBUG=verbose
	export MESA_LOG_FILE=~/ms.log
	export MESA_VK_WSI_PRESENT_MODE=fifo
	glmark2 # vkcube # glmark2

	# 清理编译过程中产生的中间文件
	ninja -C ${DIR_NAME} clean

	'
}

function sw_create_desktop_file() {
	echo ""
}

if [ "${action}" == "卸载" ]; then
	rm -rf ${SRC_DIR}
	echo "暂不支持卸载"
	exit 1
else
	sw_download
	sw_compile
	sw_create_desktop_file
fi
